﻿using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Data.Core.Plugins;
using Avalonia.Markup.Xaml;
using Avalonia.Platform;
using AvaloniaNotes.ViewModels;
using AvaloniaNotes.Views;
using System;

namespace AvaloniaNotes;

public partial class App : Application
{

    private static TrayIcon? NotifyIcon;

    public override void Initialize()
    {
        AvaloniaXamlLoader.Load(this);
    }

    public override void OnFrameworkInitializationCompleted()
    {
        // Line below is needed to remove Avalonia data validation.
        // Without this line you will get duplicate validations from both Avalonia and CT
        BindingPlugins.DataValidators.RemoveAt(0);

        if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
        {
            desktop.MainWindow = new MainWindow
            {
                DataContext = new MainViewModel()
            };
        }
        else if (ApplicationLifetime is ISingleViewApplicationLifetime singleViewPlatform)
        {
            singleViewPlatform.MainView = new MainView
            {
                DataContext = new MainViewModel()
            };
        }

        InitTrayIcon();
        
        base.OnFrameworkInitializationCompleted();
    }

    private void InitTrayIcon() 
    {
        var manageNotesMenuItem = new NativeMenuItem("管理标签");
        //var importDBMenuItem = new NativeMenuItem("导入数据库");
        //var exportDBMenuItem = new NativeMenuItem("导出数据库");
        var SeparatorMenuItem = new NativeMenuItemSeparator();
        var ExitMenuItem = new NativeMenuItem("退出");
        manageNotesMenuItem.Click += ShowWindow;
        ExitMenuItem.Click += ExitApplication;
        NotifyIcon = new TrayIcon
        {
            ToolTipText = "标签管理",
            Icon = new WindowIcon(AssetLoader.Open(new Uri("avares://AvaloniaNotes/Assets/avalonia-logo.ico"))),
            Menu = [ manageNotesMenuItem, SeparatorMenuItem, ExitMenuItem ]
        };
    }

    private void ExitApplication(object? sender, System.EventArgs e)
    {
        if (NotifyIcon != null) { 
            NotifyIcon.IsVisible = false;
        }
        Environment.Exit(0);
    }

    private void ShowWindow(object? sender, System.EventArgs e)
    {
        if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow != null)
        {
            desktop.MainWindow.Show();
            if (desktop.MainWindow.WindowState == WindowState.Minimized)
                desktop.MainWindow.WindowState = WindowState.Normal;
        }
    }
}
